﻿using System;
using System.Text.RegularExpressions;
using Birkelund.QueryStrings.Tokens;
using NUnit.Framework;

namespace Birkelund.QueryStrings.Test
{
    public class ErrorHandlingTest
    {
        [Test]
        public void EnsureProperExceptionMessage_TokenParserException()
        {
            Uri initialUrl = new Uri(@"http://localhost/test/testFile.aspx");
            var token = new ValueTypeToken<int>("id")
            {
                ExceptionNotificationBehaviour = ExceptionNotificationBehaviour.ThrowException
            };

            TokenParserException ex = Assert.Throws<TokenParserException>(() => token.ReadValue(initialUrl));
            StringAssert.Contains(ex.FailureArgs.ToString(), ex.Message); //ensures that a good error message pops up in the Message property
        }

        [Test]
        public void DoubleErrorMessage()
        {
            IQueryStringToken<bool> a = new ValueTypeToken<bool>("a");
            Uri initialUrl = new Uri(@"http://localhost/default.aspx");

            TokenParserException ex = Assert.Throws<TokenParserException>(() => a.ReadValue(initialUrl));

            //ensures that the details are only shown one time in the exception message. (has prev. been a problem)
            int count = new Regex("Details:").Matches(ex.ToString()).Count;
            Assert.AreEqual(1, count);
        }

        [Test]
        public void InvalidUrlFormatTest()
        {
            IQueryStringToken<bool> a = new ValueTypeToken<bool>("a");
            Uri initialUrl = new Uri(@"http://localhost/default.aspx?&id=123 &a=True"); //whitespace in url and empty 'null' token
            Assert.DoesNotThrow(() => a.ReadValue(initialUrl));
        }
    }
}
